﻿using System.Security.Cryptography;
using System.Text;

namespace SwaggerSdk;
public class Md5
{

    public static string Encrypt(string str, int code)
    {
        string strEncrypt = string.Empty;
        if (code == 16)
        {
            strEncrypt = Hash(str).Substring(8, 16);
        }
        if (code == 32)
        {
            strEncrypt = Hash(str);
        }
        return strEncrypt;
    }
    public static string Encrypt(string Text, string sKey)
    {
        var des = DES.Create();
        byte[] inputByteArray = Encoding.Default.GetBytes(Text);
        des.Key = Encoding.ASCII.GetBytes(Hash(sKey).ToUpper().Substring(0, 8));
        des.IV = Encoding.ASCII.GetBytes(Hash(sKey).ToUpper().Substring(0, 8));
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(), CryptoStreamMode.Write);
        cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
        cryptoStream.FlushFinalBlock();
        StringBuilder ret = new StringBuilder();
        foreach (byte b in memoryStream.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        return ret.ToString();
    }
    public static string Hash(string input)
    {
        var md5 = MD5.Create();
        byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));

        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }

}